#include "SessionHandler.h"
#include <iostream>
#include "FormatMessage.h"

#include "BasicPlugin.h"
#include "PluginLoader.h"

#include <vector>
#include "MainController.h"

int CSessionHandler::handleSession(const CMessage& message)
{
	//std::cout << "CSessionHandler::handleSession - 1" << std::endl;
	LOGDEBUG("CSessionHandler::handleSession - 1");

	std::shared_ptr<CFormatMassage> format_message;
	format_message = message.m_pHandler->getFormatData(message);
	//format_message->showData();
	LOGDEBUG("CSessionHandler::handleSession - 2");
	//std::cout << "CSessionHandler::handleSession - 2" << std::endl;
    if (!format_message)
        return 0;

	run_plugins(format_message);

	LOGDEBUG("CSessionHandler::handleSession - 3");
	//std::cout << "CSessionHandler::handleSession - 3" << std::endl;
	return 1;
}

int CSessionHandler::run_plugins(std::shared_ptr<CFormatMassage>& format_message)
{
    if (!format_message)
        return 0;
	LOGDEBUG("CSessionHandler::run_plugins - 1");
	//std::cout << "CSessionHandler::run_plugins -1" << std::endl;
	std::vector<CPluginLoader<BasicPlugin>> plugins =
		CMainController::getInstance()->getPlugins();
	for (CPluginLoader<BasicPlugin> plugin : plugins)
    {
		std::shared_ptr<BasicPlugin> ptr = plugin.getInstance();
		LOGDEBUG("CSessionHandler::run_plugins - 2");
		//std::cout << "CSessionHandler::run_plugins -2  " << ptr->getPluginName()  << std::endl;
        //std::cout << "CSessionHandler::run_plugins -3  " << format_message  << std::endl;
        //format_message->showData();
        //std::cout << "CSessionHandler::run_plugins -4  " << ptr->getPluginName()  << std::endl;
		ptr->process(format_message);
		LOGDEBUG("CSessionHandler::run_plugins - 3");
	}
	
	return 1;
}
